<template>
  <el-dialog
      v-model="visible"
      :fullscreen="isFullscreen"
      :show-close="false"
      :modal-class="dialogTransition"
      width="80%"
      top="5vh"
      destroy-on-close
      @closed="onDialogClosed"
      :style="{ '--header-height': isFullscreen ? '54px' : '60px' }"
  >
    <template #header>
      <div class="custom-header">
        <div class="connection-status">
          <span>在线客服</span>
          <el-tag :type="wsStore.isConnected ? 'success' : 'danger'" size="small">
            {{ wsStore.isConnected ? '已连接' : '连接中...' }}
            {{  wsStore.isConnected }}
          </el-tag>
        </div>
        <div class="header-buttons">
          <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'">
            <el-button
                link
                :icon="isFullscreen ? 'Aim' : 'FullScreen'"
                @click="toggleFullscreen"
            />
          </el-tooltip>
          <el-button link icon="Close" @click="visible = false"/>
        </div>
      </div>
    </template>

    <div class="chat-container" :style="{ height: containerHeight }">
      <!-- 左侧用户列表 -->
      <div class="user-list">
        <div
            v-for="user in users"
            :key="user.id"
            class="user-item"
            :class="{ active: currentUser?.id === user.id }"
            @click="selectUser(user)"
        >
          <el-avatar :src="user.avatar"/>
          <div class="user-info">
            <div class="username">{{ user.name }}</div>
            <div class="status">
              <span :class="['dot', { online: user.online }]"></span>
              <span>{{ user.online ? '在线' : '离线' }}</span>
            </div>
          </div>
          <el-badge v-if="user.unread > 0" :value="user.unread" class="unread"/>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-main">
        <!-- 聊天内容 -->
        <div ref="messagesRef" class="messages">
          <div
              v-for="(msg, index) in currentMessages"
              :key="index"
              class="message-item"
              :class="msg.sender"
          >
            <div class="message-content">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-time">{{ formatTime(msg.time) }}</div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              resize="none"
              :class="{ 'error-input': isError }"
              :disabled="!wsStore.isConnected"
              :loading="wsStore.isLoading"
              @keyup.enter.exact="sendMessage"
          />
          <div class="action">
            <el-button
                type="primary"
                @click="sendMessage"
                :disabled="!wsStore.isConnected"
                :loading="wsStore.isLoading"
            >
              {{ wsStore.isLoading ? '发送中...' : 'Enter+发送' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, nextTick, onMounted, onBeforeUnmount} from 'vue'
import dayjs from 'dayjs'
import {ElNotification} from 'element-plus'
import {useWebSocketStore} from '@/stores/websocket'

const wsStore = useWebSocketStore()

// 用户信息接口
interface User {
  id: number
  name: string
  avatar: string
  online: boolean
  unread: number
}

interface Message {
  id?: number | string;
  time: number;
  message_id: string
  userId: number
  content: string
  timestamp: number
  sender: 'user' | 'service'
}

interface ChatMessage {
  action: 'text' | 'image' | 'file'
  // method: 'CS_REPLY' | 'MSG_RECEIPT' | 'CS_MSG'
  content: string
  userId?: number
  timestamp: number
}

/* ---------- 组件状态管理 ---------- */
const isFullscreen = ref(false)
const visible = ref(false)
const isAnimating = ref(false)
const messages = ref<Message[]>([])
const currentUser = ref<User>()
const inputMessage = ref('')
const messagesRef = ref<HTMLElement>()
const isError = ref(false)


// 接收用户消息
// wsStore.on('MSG_RECEIPT', (data) => {
  // console.log('收到用户消息:', data)
  // if (msg.type === 'service_message' && msg.userId) {
  //   const targetUser = users.value.find(u => u.id === msg.userId)
  //   if (!targetUser) return
  //
  //   const newMessage: Message = {
  //     id: Date.now(),
  //     userId: msg.userId,
  //     content: msg.content,
  //     time: msg.timestamp,
  //     sender: 'service'
  //   }
  //
  //   // 更新消息列表
  //   messages.value.push(newMessage)
  //
  //   // 更新未读计数
  //   if (currentUser.value?.id !== msg.userId) {
  //     targetUser.unread++
  //   }
  //
  //   // 滚动到底部
  //   nextTick(scrollToBottom)
  // }
// })

/* ---------- 模拟用户数据 ---------- */
const users = ref<User[]>([
  {
    id: 1,
    name: '客服1',
    avatar: 'https://example.com/avatar1.png',
    online: true,
    unread: 0
  },
  // 更多客服...
])

/* ---------- 计算属性与方法 ---------- */
const containerHeight = computed(() =>
    isFullscreen.value ? 'calc(100vh - var(--header-height))' : '60vh'
)

const dialogTransition = computed(() =>
    isAnimating.value ? 'dialog-transition' : ''
)

const currentMessages = computed(() =>
    messages.value.filter(msg => msg.userId === currentUser.value?.id)
)

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  nextTick(scrollToBottom)
}

const open = () => {
  visible.value = true
  isAnimating.value = true
  if (users.value.length > 0) selectUser(users.value[0])
}

const onDialogClosed = () => {
  isAnimating.value = false
}

const selectUser = (user: User) => {
  currentUser.value = user
  user.unread = 0
  nextTick(scrollToBottom)
}


// 接收消息
wsStore.on('MSG_RECEIPT', (data) => {
  console.log('收到用户消息:', data)

})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return (isError.value = true)
  // if (!currentUser.value || !wsStore.isConnected.value) return

  try {
    // 发送消息模板
    const payload: ChatMessage = {
      action: 'text',
      content: inputMessage.value,
      userId: currentUser.value.id,
      timestamp: Date.now()
    }

    wsStore.send('CS_REPLY', payload)

    messages.value.push({
      id: String(Date.now()),
      userId: currentUser.value.id,
      content: inputMessage.value,
      time: Date.now(),
      sender: 'user',
      message_id: '',
      timestamp: 0
    })

    inputMessage.value = ''
    scrollToBottom()
  } catch (error) {
    ElNotification.error('消息发送失败')
  }
}

const scrollToBottom = () => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

const formatTime = (timestamp: number) => dayjs(timestamp).format('HH:mm')

/* ---------- 生命周期管理 ---------- */
onMounted(() => {
  window.addEventListener('resize', scrollToBottom)
})

// 组件卸载
onBeforeUnmount(() => {
  window.removeEventListener('resize', scrollToBottom)
})

defineExpose({open})
</script>

<style lang="scss">
.el-dialog.is-fullscreen {
  overflow: hidden !important;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-tag {
    margin-left: 8px;
  }
}

:deep(.is-disabled) {
  .el-textarea__inner {
    background-color: #f5f7fa;
    cursor: not-allowed;
  }
}
</style>

<style scoped lang="scss">
.chat-container {
  display: flex;
  gap: 16px;
  width: 100%;
  height: inherit;

  .user-list {
    flex: 0 0 240px;
    border-right: 1px solid #eee;
    overflow-y: auto;
    padding-right: 8px;
    min-width: 200px;
    max-width: 30vw;

    .user-item {
      display: flex;
      align-items: center;
      padding: 12px;
      cursor: pointer;
      position: relative;
      transition: all 0.3s;

      &:hover {
        background: #f5f7fa;
      }

      &.active {
        background: #ecf5ff;
      }

      .user-info {
        margin-left: 12px;
        flex: 1;

        .username {
          font-weight: 500;
        }

        .status {
          font-size: 12px;
          color: #999;

          .dot {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #ccc;
            margin-right: 4px;

            &.online {
              background: #67c23a;
            }
          }
        }
      }

      .unread {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }

  .chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 300px;
    overflow: hidden;

    .messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      background: #f8f9fa;
      border-radius: 4px;
      scroll-behavior: smooth;
      scrollbar-width: thin;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #c1c1c1;
        border-radius: 3px;
      }

      .message-item {
        margin-bottom: 16px;

        &.user {
          display: flex;
          justify-content: flex-end;

          .message-content {
            background: var(--el-color-primary);
            color: white;
          }
        }

        &.service {
          .message-content {
            background: white;
            border: 1px solid #eee;
          }
        }

        .message-content {
          max-width: 70%;
          padding: 8px 12px;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          .message-time {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
          }
        }
      }
    }

    .input-area {
      position: sticky;
      bottom: 0;
      background: white;
      padding: 16px 0;
      z-index: 1;
      box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

      .action {
        margin-top: 8px;
        text-align: right;
      }
    }
  }
}

.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 40px;

  .header-buttons {
    display: flex;
    gap: 8px;

    :deep(.el-button) {
      padding: 0;
      border: none;
      color: var(--el-text-color-regular);

      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
}

:deep(.dialog-transition) {
  .el-dialog {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    transform-origin: center center;
    will-change: transform, opacity;
  }

  .el-overlay {
    transition: all 0.3s ease-in-out;
  }

  &.el-dialog-enter-active {
    .el-overlay {
      animation: fadeIn 0.3s;
    }

    .el-dialog {
      animation: zoomIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }

  &.el-dialog-leave-active {
    .el-overlay {
      animation: fadeOut 0.3s;
    }

    .el-dialog {
      animation: zoomOut 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

@keyframes zoomIn {
  from {
    transform: scale(0.95) translateY(20px);
    opacity: 0;
  }
  to {
    transform: scale(1) translateY(0);
    opacity: 1;
  }
}

@keyframes zoomOut {
  from {
    transform: scale(1);
    opacity: 1;
  }
  to {
    transform: scale(0.95) translateY(20px);
    opacity: 0;
  }
}

:deep(.error-input) {
  .el-textarea__inner {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
    transition: all 0.3s;
  }
}
</style>